#include "config.h"
#include <QDebug>

using namespace std;

Config::Config() {

    QString fileName = "./config.ini";
    
    //读取文件信息
    try {
        m_settings = new QSettings(fileName, QSettings::IniFormat);
        m_settings->beginGroup("xserial");
        QStringList keys = m_settings->allKeys();
        for(QString key: keys){
            m_directs.insert(key, m_settings->value(key, "").toString());
        }
        m_settings->endGroup();
    } catch (const exception& e) {
        qCritical() << e.what();
        qCritical() << e.what();
    } catch (...) {
        qCritical() << "unknow error...";
    }
}

Config::~Config() {}

Config &Config::getInstance() {
    static Config config;
    return config;
}

QMap<QString, QString> &Config::directs() {
    return m_directs;
}

void Config::addDirect(QString key, QString val) {
    if (!val.isEmpty()) {
        m_directs.insert(key, val);
        saveDirects();
    }
}

void Config::deleteDirect(QString key) {
    m_directs.remove(key);
    saveDirects();
}

void Config::saveDirects() {
    m_settings->beginGroup("xserial");
    QStringList keys = m_directs.keys();
    for (QString& key : keys) {
        m_settings->setValue(key, m_directs[key]);
    }
    m_settings->endGroup();
    m_settings->sync();
}
